package com.wry.consumer;

import com.wry.api.SpikeService;
import com.wry.entity.Goods;
import com.wry.entity.Order;
import com.wry.enums.OrderStatusEnum;
import com.wry.service.GoodsService;
import com.wry.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * <h1>  <h1>
 *
 * @author 魏如元
 * @since 2022/7/18
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "ORDER_CHECK_TOPIC",consumerGroup = "group-check")
public class CheckOrderConsumer implements RocketMQListener<String> {

    @Resource
    private OrderService orderService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private SpikeService spikeService;

    @Override
    public void onMessage(String msg) {
        final Order order = orderService.lambdaQuery()
                .eq(Order::getOrderId, msg)
                .one();
        log.info("order ===> {}",order);
        if (Objects.isNull(order)){
            return;
        }
        log.info("-----------开始检查订单【{}】状态---------",order.getOrderId());
        // 检查订单状态，若还未支付，取消订单恢复库存
        if (OrderStatusEnum.PAYING.name().equals(order.getStatus())){
            // 恢复库存
            final Goods goods = goodsService.lambdaQuery()
                    .eq(Goods::getId, order.getGoodsId())
                    .one();
            Integer num = goods.getNum();
            goods.setNum(++num);
            goodsService.updateById(goods);
            // 更新订单状态为已取消
           order.setStatus(OrderStatusEnum.CANCEL.name());
           orderService.updateById(order);
           // 更新缓存中库存
            spikeService.sync();
           log.info("--------{}-超时未支付恢复库存------当前库中库存：{}-------",order.getOrderId(),goods.getNum());
        }else {
            log.info("----------【{}】订单状态为：【{}】，无需操作",order.getOrderId(),order.getStatus());
        }

        }
}
